﻿// -----------------------------------------------------------------------
// <copyright file="DotNetConfigSource.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace NetFramework.Configuration.ConfigSource
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Configuration;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class DotNetConfigSource : ConfigSourceBase
    {
        private static DotNetConfigSource instance;

        static DotNetConfigSource()
        {
            instance = new DotNetConfigSource();
        }

        public static DotNetConfigSource Current
        {
            get
            {
                return instance;
            }
        }

        public DotNetConfigSource()
            : base()
        {
        }

        protected override T GetConfigFromSource<T>(IConfigParameter parameter)
        {
            System.Configuration.Configuration configuration = GetConfiguration(parameter.Files[0]);
            return configuration.GetSection(parameter.Name) as T;
        }

        /// <summary>
        /// 获取DotNet配置
        /// </summary>
        /// <param name="fileName">配置文件路径。</param>
        /// <returns>DotNet配置</returns>
        private static System.Configuration.Configuration GetConfiguration(string fileName)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        }
    }
}
